import Book from '../types/Book';
import { MongoBook } from './BookModel';
import { BookModel } from './index';
import { transform, validate } from '../utils';

const bookManager = {
    async add(book: Book): Promise<MongoBook | string[]> {
        if (!(book instanceof Book)) {
            book = transform(Book, book);
        }
        const errors = await validate(book);
        if (errors.length > 0) return errors;
        return await BookModel.create(book);
    },
    async remove(id: string): Promise<void> {
        await BookModel.deleteOne({ _id: id });
    },
    async edit(id: string, newBook: Book): Promise<void | string[]> {
        if (!(newBook instanceof Book)) {
            newBook = transform(Book, newBook);
        }
        const errors = await validate(newBook);
        if (errors.length > 0) return errors;
        await BookModel.updateOne({ _id: id }, newBook);
    },
    async findById(id: string): Promise<MongoBook | null> {
        return await BookModel.findById(id);
    },
};

export default bookManager;
